package com.yc.psychologicalconsultant.validator;

import com.yc.psychologicalconsultant.utils.ValidatorUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;

/**
 * @author YC
 * @version 1.0
 */
public class IsEmailValidator implements ConstraintValidator<IsEmail, String> {
    private boolean required = true;

    // 初始化
    @Override
    public void initialize(IsEmail constraintAnnotation) {
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required) { // 必填
            return ValidatorUtil.isEmail(value);
        } else { // 非必填
            if (!StringUtils.hasText(value)) return true;
            else return ValidatorUtil.isEmail(value);
        }
    }
}
